package com.project.common.Security;

import com.project.common.constant.JwtConstant;
import com.project.controller.AssetController;
import com.project.entity.Users;
import com.project.service.UsersService;
import com.project.util.CheckResult;
import com.project.util.JwtUtils;
import com.project.util.StringUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * 请求过滤器
 *
 * @author Leo高洋
 * @create 2023-01-17 0:17
 */
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
    @Autowired
    UsersService usersService;

    @Autowired
    private MyUserDetailsServiceImpl myUserDetailsService;

    private final static Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    private static final String[] URL_WHITELIST = {
            "/login",
            "/logout",
            "/captcha",
            "/password",
            "/image/**",
            "/contract/**",
            "/doc/**"
    };

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        logger.info("请求url:" + request.getRequestURI());
        // 如果token是空 或者 url在白名单里，则放行
        if (StringUtil.isEmpty(token) ||
                new ArrayList<String>
                        (Arrays.asList(URL_WHITELIST)).
                        contains(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
        //校验token的合法性
        CheckResult checkResult = JwtUtils.validateJWT(token);
        //如果校验失败，则返回如下信息
        if (!checkResult.isSuccess()) {
            switch (checkResult.getErrCode()) {
                case JwtConstant.JWT_ERRCODE_NULL:
                    throw new JwtException("Token不存在");
                case JwtConstant.JWT_ERRCODE_FAIL:
                    throw new JwtException("Token验证不通过");
                case JwtConstant.JWT_ERRCODE_EXPIRE:
                    throw new JwtException("Token过期");
            }
        }
        //解析token数据
        Claims claims = JwtUtils.parseJWT(token);
        //从token数据中获取用户名
        String username = claims.getSubject();
        Users users = usersService.getByUsername(username);
        //检验成功，返回响应数据
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(username, null,
                        myUserDetailsService.getUserAuthority());

        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        chain.doFilter(request, response);
    }
}
